package ynu.edu.achitecturework.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import ynu.edu.achitecturework.common.result.Result;
import ynu.edu.achitecturework.entity.Device;
import ynu.edu.achitecturework.entity.SensorData;
import ynu.edu.achitecturework.service.DeviceService;

import java.util.List;

@RestController
@RequestMapping("/api/devices")
@RequiredArgsConstructor
@Slf4j
public class DeviceController {

    private final DeviceService deviceService;

    @GetMapping
    public Result<List<Device>> getAllDevices() {
        return Result.success(deviceService.getAllDevices());
    }

    @GetMapping("/greenhouse/{greenhouseId}")
    public Result<List<Device>> getDevicesByGreenhouse(@PathVariable Long greenhouseId) {
        log.info("获取大棚 {} 的设备列表", greenhouseId);
        try {
            List<Device> devices = deviceService.getDevicesByGreenhouse(greenhouseId);
            log.info("找到 {} 个设备", devices.size());
            return Result.success(devices);
        } catch (Exception e) {
            log.error("获取设备列表失败", e);
            return Result.error(500, "获取设备列表失败: " + e.getMessage());
        }
    }

    @GetMapping("/{deviceId}/sensor-data")
    public Result<List<SensorData>> getRecentSensorData(@PathVariable Long deviceId) {
        log.info("获取设备 {} 的最近传感器数据", deviceId);
        try {
            List<SensorData> sensorData = deviceService.getRecentSensorData(deviceId);
            log.info("找到 {} 条传感器数据", sensorData.size());
            return Result.success(sensorData);
        } catch (Exception e) {
            log.error("获取传感器数据失败", e);
            return Result.error(500, "获取传感器数据失败: " + e.getMessage());
        }
    }
    @GetMapping("/{deviceId}/sensor-data/latest")
    public Result<SensorData> getLatestSensorData(@PathVariable Long deviceId) {
        log.info("获取设备 {} 的最新传感器数据", deviceId);
        try {
            SensorData sensorData = deviceService.getLatestSensorData(deviceId);
            return Result.success(sensorData);
        } catch (Exception e) {
            log.error("获取最新传感器数据失败", e);
            return Result.error(500, "获取最新传感器数据失败: " + e.getMessage());
        }
    }
}